<template>
  <div class="contentTextContainers">
    <div class="main-con">
      <el-form :model="ruleForm"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <div v-if="showSearchCondition">
          <el-row>
            <el-col :span="6">
              <el-form-item label="开始时间">
                <el-date-picker
                  size="medium"
                  v-model="ruleForm.startTime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结束时间">
                <el-date-picker
                  size="medium"
                  v-model="ruleForm.endTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单时间">
                <el-date-picker
                  size="medium"
                  v-model="ruleForm.orderTime"
                  type="date"
                  format="yyyy-MM-dd "
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单状态">
                <el-select v-model="ruleForm.orderStatus" placeholder="请选择" size="medium" clearable>
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="订单平台">
                <el-select v-model="ruleForm.channelCode" placeholder="请选择" size="medium"  filterable allow-create clearable>
                  <el-option
                    v-for="item in list"
                    :key="item.id"
                    :label="item.channelName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单公司">
                <el-select v-model="ruleForm.companyCode" placeholder="请选择"  size="medium" filterable allow-create clearable>
                  <el-option
                    v-for="item in tableData3"
                    :key="item.id"
                    :label="item.companyName"
                    :value="item.companyCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品名称">
                <el-input v-model="ruleForm.channelItemName" size="medium" placeholder="请输入姓名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="姓名">
                <el-input v-model="ruleForm.receiverName" size="medium" placeholder="请输入姓名" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="6">
              <el-form-item label="联系方式">
                <el-input v-model="ruleForm.receiverPhone"  size="medium" placeholder="请输入联系方式" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单编号">
                <el-input placeholder="请输入订单编号" v-model="ruleForm.orderId" size="medium" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col  :span="6">
              <el-form-item label="快递单号" >
                <el-input type="text" placeholder="请输入订单编号" v-model="ruleForm.expressCode"  size="medium"  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item  >
                <el-button type="primary" @click="query" size="small" style="margin-left: -40px!important;">查询</el-button>
                <el-button @click="resetForm('ruleForm')" size="small">重置</el-button>
                <span v-if="isSearch === true"  @click="simple" style="color:#3c8dbc"><i class="iconfont">&#xe620;</i>高级搜索</span>
                <span v-else @click="simpleA" style="color:#3c8dbc;margin-left:10px;" ><i class="iconfont">&#xe620;</i>简单搜索</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-row v-if="isSearch">
          <el-col :span="6">
            <el-form-item label="订单平台">
              <el-select v-model="ruleForm.channelCode" placeholder="请选择" size="medium"  filterable allow-create clearable>
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.channelName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单公司">
              <el-select v-model="ruleForm.companyCode" placeholder="请选择"  size="medium" filterable allow-create clearable>
                <el-option
                  v-for="item in tableData3"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.companyCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="query" size="small">查询</el-button>
              <el-button @click="resetForm('ruleForm')" size="small">重置</el-button>
              <span v-if="isSearch === true"  @click="simple" style="color:#3c8dbc;margin-left:20px;"><i class="iconfont">&#xe620;</i>高级搜索</span>
              <span v-else @click="simpleA" style="color:#3c8dbc;margin-left:20px;" ><i class="iconfont">&#xe620;</i>简单搜索</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="stand">
      <div class="middleModule">
        <div class="selectDate">
          <div class="block">
            <el-tooltip class="item" effect="dark" content="发货单导出" placement="top-start">
              <el-button icon="el-icon-upload2" @click="exportInvoices" size="small" type="warning"></el-button>
            </el-tooltip>
            <div class="orderUPload">
              <el-upload
                class="upload-demo"
                action="/api/erp/v1/order/upload"
                :on-success="onSuccess"
                :on-error="onError"
                :data={userId:this.userId}
                accept=".xls,.xlsx">
                <el-tooltip class="item" effect="dark" content="订单导入" placement="top-start">
                  <el-button size="small"  icon="el-icon-upload"></el-button>
                </el-tooltip>
              </el-upload>
            </div>
            <div class="invoiceOrder">
              <el-upload
                class="upload-demo"
                action="/api/erp/v1/order/delivery/upload"
                :on-success="onSucc"
                :on-error="onErr"
                :data={userId:this.userId}
                accept=".xls,.xlsx">
                <el-tooltip class="item" effect="dark" content="发货单导入" placement="top-start">
                  <el-button size="small"  icon="el-icon-download" type="primary"></el-button>
                </el-tooltip>
              </el-upload>
            </div>
          </div>
        </div>
        <div class="orderTable">
          <el-table
            :data="allOrderList"
            highlight-current-row
            :header-cell-style="getRowClass"
            style="width: 100%"
            @cell-dblclick="celldblclick">
            <el-table-column
              :show-overflow-tooltip="true"
              prop="channelName"
              label="订单平台"
              width="100">
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="companyName"
              label="订单公司" >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="depotName"
              label="储仓"
              width="80" >
            </el-table-column>
            <el-table-column
              prop="orderId"
              label="订单编号"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="orderTime"
              label="订单时间" >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="orderStatus"
              label="订单状态"
              width="80">
            </el-table-column>
            <el-table-column
              prop="receiverName"
              label="姓名"
              width="80">
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="receiverPhone"
              label="联系方式"
              width="110" >
            </el-table-column>
            <el-table-column
              width="150"
              prop="channelItemName"
              label="渠道商品名称"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
              prop="purchaseNum"
              label="购买数量"
              width="80" >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="orderMoney"
              label="订单金额"
              width="80" >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="expressCode"
              label="发出单号"
              width="80" >
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="180">
              <template slot-scope="scope">
                <el-button size="mini" type="text"   @click="lookOrder(scope.row.id)"><span>查看</span></el-button>
                <el-button type="text"   size="mini" @click="del(scope.row.id)"><span>删除</span></el-button>
                <el-button type="text"    size="mini" @click="updateStatus(scope.row.id)"><span>更新</span></el-button>
                <el-button type="text" v-if="scope.row.export == false"  size="mini" @click="grow(scope.row.id)"><span>生成</span></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="pagination">
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[10]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount">
        </el-pagination>
      </div>
    </div>
    <!-- 订单导入 -->
    <import-invoice v-if="isShowOrder" :num="num" :failNum="failNum" :failOrders="failOrders"  @closeTip="closeTip"></import-invoice>
    <!-- 发货单弹框 -->
    <import-bill v-if="isShowBill" :number="number" :failNumber="failNumber" :failDeliveryOrders="failDeliveryOrders"  @closeTip="closeTip"></import-bill>
  </div>
</template>
<script>
  import SplitVertical from "components/common/SplitVertical"
  import api from 'js/service'
  import axios from 'axios'
  import {localStorage} from 'js/localStorage'
  import { Loading } from 'element-ui';
  import importInvoice from 'components/base/OrderQuery/Importinvoice.vue'
  import importBill from 'components/base/OrderQuery/ImportBill.vue'
  export default {
    inject:['reload'],
    data(){
      return{
        showSearchCondition:false,
        isSearch:true,
        //v-model
        ruleForm:{
          startTime:'',
          endTime:'',
          orderId:'',
          expressCode:'',
          orderTime:'',
          orderStatus:'',
          companyCode:'',
          channelCode:'',
          receiverName:'',
          receiverPhone:'',
          channelItemName:'',
        },
        //页码
        pageCount: 0,
        pageIndex:1,
        pageSize:10,
        list:[],
        carryData:[],
        tableData3:[],
        allOrderList:[],
        options:[
          {value:"待发货",label:'待发货'},
          {value:"已发货",label:'已发货'},
          {value:"已完成",label:'已完成'},
          {value:"已退货",label:'已退货'},
          // {value:"已退款",label:'华住订单'}
        ],
        value:'',
        jumpShow:false,
        showLook:true,
        failNum:"",
        num:"",
        failOrders:[],
        isShowOrder:false,
        isShowBill:false,
        failNumber:'',
        number:'',
        failDeliveryOrders:[],
      }
    },
    created(){
      this.init()
    },
    methods:{
      init(){
        this.userId=localStorage.get('userID')
        this.query()
        this.listVal()
        this.orderCompany()
      },
      simple(){
        this.showSearchCondition=true
        this.isSearch=false
      },
      simpleA(){
        this.showSearchCondition=false,
        this.isSearch=true
      },
      onSuccess(response, file, fileList){
        if(response.code === "OK"){
          this.isShowOrder=true
          this.failNum=response.data.failNum,
          this.num=response.data.number
          this.failOrders=response.data.entities
        }else{
          this.$message.warning(response.msg)
        }
      },
      onError(err, file, fileList){
        // console.log(err, file, fileList,"ddd")
      },
      //生成发货单
      grow(id){
        let parmas={
          id:id,
          userId:this.userId
        }
        let success=data=>{
          if(data.code=="OK"){
            this.$message.success("生成发货单成功")
            this.query()
          }else{
            this.$message.error(data.msg)
          }
        }
        api.orderCreateOut(parmas,success)
      },
      //设置表格第一行的颜色
      getRowClass({row, column, rowIndex, columnIndex}) {
        if (rowIndex == 0) {
          return 'background:#fafafa;color:rgba(0, 0, 0, 0.85)'
        } else {
          return ''
        }
      },
      //实现双击复制
      celldblclick (row, column, cell, event) {
        var _this=this
        this.$copyText(row[column.property]).then(function (e) {
          _this.$message.success("复制成功")
        }, function (e) {
        })
      },
      closeTip(){
        this.isShowOrder=false
        this.reload()
        this.isShowBill=false
        this.reload()
      },
      //更新状态
      updateStatus(id){
        this.tips.ConfirmModal('此操作将更新订单状态,是否继续？', () => {
          let parmas={
            id:id
          }
          let success=data=>{
            if(data.code=='OK'){
              this.$message.success("更新状态成功")
              this.reload()
            }else{
              this.$message.error(data.msg)
            }
          }
          api.orderUpdateStatus(parmas,success)
        });
      },
      onSucc(response, file, fileList){
        if(response.code === "OK"){
          this.isShowBill=true
          this.failNumber=response.data.failNum
          this.pageCount=response.pageCount
          this.number=response.data.number
          this.failDeliveryOrders=response.data.entities
        }else{
          this.$message.warning(response.msg)
        }
      },
      onErr(err, file, fileList){

      },
      //发货单导出
      exportInvoices(){
        for(var i in this.orderTime){
          this.startTime = this.orderTime[0];
          this.endTime = this.orderTime[1];
        }
        this.$confirm('此操作导出出库单,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //优化
          // let loadingInstance = Loading.service({ fullscreen: true,text:'正在导出中，请稍后..' });
          axios({
            method:'get',
            url: '/api/erp/v1/order/delivery/download',
            responseType: 'blob',
            timeout:1000 * 60 * 10,
            params:{
              startTime:this.startTime,
              endTime:this.endTime,
              userId:this.userId
            }
          }).then(res => {
            if(res.status == "200"){
              const link = document.createElement('a')
              let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
              link.style.display = 'none'
              link.href = URL.createObjectURL(blob);
              link.setAttribute('download', '发货单' + '.xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
              this.reload()
            }else{
              this.$message.error("数据错误")
            }
          }).catch(error => {
            this.$message.warning("网络链接错误")
          })
        });
      },
      orderCompany(){
        let success=data=>{
          if(data.code=='OK'){
            this.tableData3= data.data
          }else{
            this.$message.error(data.msg)
          }
        }
        api.companyAll({},success)
      },
      listVal(){
        let success=data=>{
          if(data.code=='OK'){
            this.list=data.data
          } else{
            this.$message.error(data.msg)
          }
        }
        api.channelAll({},success)
      },
      //导入订单
      upload(e){
        let file = e.target.files[0];
        let size=file.size;
        let name=file.name
        if(name.indexOf("xlsx")<0){
          return this.$message.error('只能导入excel格式的文件')
        }
        if(size>5000000){
          return  this.$message.error('请选择5M以内的文件')
        }
        var parma = new FormData() //创建form对象
        parma.append('file',file,file.name);//通过append向form对象添加数据
        parma.append('userId',this.userId);
        let loadingInstance = Loading.service({ fullscreen: true,text:'正在导入中，请稍后..' });
        let success=data=>{
          if(data.code=='OK'){
            this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
            this.isShowOrder=true
            this.failNum=data.data.failNum,
            this.num=data.data.number
            this.failOrders=data.data.entities
            this.$message.success('导入成功')
            // this.reload()
          }else{
            this.$message.error(data.msg)
            this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
          }
        }
        api.orderUpload(parma,success)
      },
      //查询所有订单
      query(){
        let parmas=this.ruleForm
        parmas['pageIndex']=1
        parmas['pageSize']=10
        let success=data=>{
          if(data.code=='OK'){
            this.allOrderList=data.data
            this.pageCount=data.pageCount
          }else{
            this.$message.error(data.msg)
          }
        }
        api.erpOrderList(parmas,success)
      },
      //重置
      resetForm(){
          this.ruleForm={}
      },
      //查看订单
      lookOrder(id){
        this.$router.push({
          path:'/order-query-detail',
          query:{
            id:id
          }
        })
      },
      handleCurrentChange(val) {
        let parmas=this.ruleForm
          parmas['pageIndex']=val
          parmas['pageSize']=10
        let success=data=> {
          if (data.code == 'OK') {
            this.allOrderList = data.data
          } else {
            this.$message.error(data.msg)
          }
        }
      this.api.erpOrderList(parmas,success)
      },
      //删除
      del(id){
        this.$confirm('是否删除该消息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          //删除诉单列表信息
          let parmas={
            id:id
          }
          let success=data=>{
            if(data.code=='OK'){
              this.reload()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }else{
              this.$message.error(data.msg)
            }
          }
          api.erpOrderDelete(parmas,success)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          });
        });
      }
    },
    components:{
      importInvoice,importBill,SplitVertical
    }
  }
</script>
<style lang="scss" scoped>
  .contentTextContainers{
    .main-con {
      background: #fff;
      height: auto;
      border-left: 2px solid #e8e8e8;
      border-right: 2px solid #e8e8e8;
      border-bottom: 2px solid #e8e8e8;
      .el-form-item{
        margin-bottom: 13px!important;
      }
      .el-input {
        width: 96%;
      }
      .el-select {
        width: 96%;
      }
    }
    .middleModule{
      position: relative;
      .selectDate{
        margin-top:5px;
        display: flex;
        width:100%;
        flex-direction: row;
        box-sizing: border-box;
        flex-wrap: wrap;
        background: #fff;
        .block{
          margin-top:5px;
          line-height:50px;
          // flex:1;
          span{
            width:75px;
            text-align: center;
            display: inline-block;
            color:#606266;
            font-size:15px;
          }
          label{
            width:100px;
            text-align: center;
            display: inline-block;
            color:#606266;
            font-size:15px;
          }
          .createBtn{
            background:#fff;
            position: relative;
            display: inline-block;
            .blueButton{
              position: absolute;
              display: inline-block;
              width: 85px;
              height: 34px;
              line-height:32px;
              background-color: #409EFF;
              border:1px solid #DCDFE6;
              color: #fff;
              text-decoration: none;
              text-align: center;
              font: normal normal normal 16px/33px 'Microsoft YaHei';
              cursor: pointer;
              border-radius: 4px;
              top: -23px;
              left: 0;
              font-size:14px;
            }
            button{
              width:70px;
              height:39px;
              border-radius: 5px;
              background:#fff;
              border:1px solid #d4d4d4;
              /*margin-left:100px;*/
              cursor: pointer;
            }
            input{
              position: absolute;
              top:-25px;
              display: block;
              width: 100px;
              height: 40px;
              opacity: 0;
              left: 17px;
              cursor: pointer;
            }
          }
          .import{
            background:#fff;
            position: relative;
            display: inline-block;
            .blueButton{
              position: absolute;
              display: inline-block;
              width: 97px;
              height: 34px;
              line-height:32px;
              border:1px solid #DCDFE6;
              color: #606266;
              text-decoration: none;
              text-align: center;
              font: normal normal normal 16px/33px 'Microsoft YaHei';
              cursor: pointer;
              border-radius: 4px;
              top: -23px;
              left: 94px;
              font-size:14px;
            }
            button{
              width:70px;
              height:39px;
              border-radius: 5px;
              background:#fff;
              border:1px solid #d4d4d4;
              /*margin-left:150px;*/
              cursor: pointer;
            }
            input{
              position: absolute;
              top:-25px;
              display: block;
              width: 100px;
              height: 40px;
              opacity: 0;
              left: 98px;
              cursor: pointer;
            }
          }
        }
      }
      .orderTable{
         margin: 0 10px;
      }
    }
    .invoiceOrder{
      position: absolute;
      left:120px;
      top: 1%;
    }
    .orderUPload{
      position: absolute;
      left: 60px;
      top: 1%;
    }
    .pagination{
      padding: 10px 0;
      text-align: right;
    }
  }
</style>
